package com.commodity.common;


import com.commodity.entity.User;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebFilter("/*")
public class LoginFilter implements Filter {
    public static final String LOGIN_KEY = "#current_user";
    private static final List<String> WHITE = List.of("/user/login/**",
            "/user/logout/**","/user/captcha",
            "/**/*.js","/**/*.css","/**/*.jpg","/**/*.png","/**/*.gif");
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        HttpSession session = req.getSession();

        String uri = req.getRequestURI();
        String ctx = req.getContextPath();
        String action = uri.replace(ctx,"");

        boolean pass = false;//是否是白名单

        PathMatcher matcher = new AntPathMatcher();
        for(String url:WHITE){
            if(matcher.match(url,action)){
                pass = true;
                break;
            }
        }

        if (pass){
            filterChain.doFilter(req,resp);
        }else{
            User user = (User) session.getAttribute(LOGIN_KEY);
            if (user==null){
                resp.sendRedirect(req.getContextPath()+"/user/login");
            }else {
                filterChain.doFilter(req,resp);
            }
        }
    }
}
